package com.ben.tcptester.Entity;

import com.ben.tcptester.exception.ClientException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Peter on 2017/7/17.
 */
public class Server {
    private static Logger logger = Logger.getLogger(Server.class);
    private String id;
    private String name;
    private String host;
    private int port;
    private String wsSessionId;
    private List<Client> clients = new ArrayList<>();

    public String getWsSessionId() {
        return wsSessionId;
    }

    public void setWsSessionId(String wsSessionId) {
        this.wsSessionId = wsSessionId;
    }

    public Server() {
        this.id = UUID.randomUUID().toString();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public List<Client> getClients() {
        return clients;
    }

    public void setClients(List<Client> clients) {
        this.clients = clients;
    }

    public synchronized void addClient(Client client) {
        clients.add(client);
    }

    public synchronized boolean removeClient(Client client) {
        return clients.remove(client);
    }

    public synchronized boolean removeClient(String clientId) {
        Client client = new Client(clientId);
        return this.removeClient(client);
    }

    public void send(String data) throws ClientException {
        if (clients.size() == 0) {
            throw new ClientException(1001, "发送报文失败（没有连接服务器）");
        }
        Client client = clients.get(0);
        if (client.getChannel() == null) {
            throw new ClientException(1002, "发送报文失败（没有连接服务器）");
        }
        if (!client.getChannel().isActive()) {
            throw new ClientException(1003, "发送报文失败（没有连接服务器）");
        }
        client.getChannel().writeAndFlush(data).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    logger.info("报文发送成功");

                } else {
                    logger.info("报文发送失败,原因为 {}", future.cause());
                }
            }
        });
    }

    // 界面用户主动断开连接
    public void disconnect(String clientId) throws ClientException {

        if (clients.size() == 0) {
            throw new ClientException(1001, "没有连接服务器");
        }
        Client client = clients.get(0);
        Channel channel = client.getChannel();
        if (channel == null) {
            throw new ClientException(1002, "没有连接服务");
        }
        if (!channel.isActive()) {
            throw new ClientException(1003, "没有连接服务器");
        }
        if(channel.isOpen()){
            channel.close();
        }else{
            throw new ClientException(1004, "已关闭");
        }
    }
}
